/**
 * 
 */
package idv.takeshi.software.productline.bookstore.presentation.web.controller;

import java.util.Locale;

import javax.validation.Valid;

import idv.takeshi.software.productline.bookstore.application.service.PayCreditCardService;
import idv.takeshi.software.productline.bookstore.domain.model.order.CreditCard;
import idv.takeshi.software.productline.bookstore.domain.model.order.Order;
import idv.takeshi.software.productline.bookstore.presentation.dto.CreditCardDto;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

/**
 * A Controller for paying by credit card operations.
 * @author takeshi
 *
 */
@Controller("payCreditCardController")
@RequestMapping("/payment")
@SessionAttributes({"order", "seeOrderDetailsInfo"})
public class PayCreditCardController {
	
	private static final Log log = LogFactory.getLog(PayCreditCardController.class);
	
	@Autowired
	private PayCreditCardService payCreditCardService;
	
	@RequestMapping(value = "/payByCreditCard.html", method = RequestMethod.GET)
	public void createCreditCardDto(
		@RequestParam Long orderId, @RequestParam String previousPath,
		ModelMap modelMap){
		
		Order order = this.payCreditCardService.getOrderById(orderId);
		CreditCardDto creditCardDto = new CreditCardDto();
		
		log.debug("previousPath = " + previousPath);
		
		creditCardDto.setPreviousPath(previousPath);
		order.toString();
		modelMap.put("order", order);
		modelMap.put("creditCardDto", creditCardDto);
	}
	
	@RequestMapping(value = "/checkAndFillCreditCard.html", method = RequestMethod.POST)
	public String checkAndFillCreditCardInfo(
			@ModelAttribute("creditCardDto") @Valid final CreditCardDto creditCardDto,
			final BindingResult result, ModelMap modelMap, Locale locale){
		Order order = (Order) modelMap.get("order");
		Long orderId = null;
		StringBuffer url = new StringBuffer();
		
		if(result.hasErrors()){
			return "/payment/payByCreditCard";
		}
		creditCardDto.fillModel((CreditCard)order.getPayment());
		this.payCreditCardService.updateCreditCard(order, locale);
		
		orderId = order.getId();
		
		url.append("redirect:" + creditCardDto.getPreviousPath() + "?orderId=" + orderId);
		return url.toString();
	}

}
